<template>
    <div class="main" :style="style" ref="hz" @scroll="scroll">
        <table ref="table">
            <thead style="border: 1px solid #000;" class="table-head"
                ref="tableHead">
         
                <tr style="border: 1px solid #000;">
                    <th style="position: sticky; top: 0; background-color: #fff;text-align:center;border:1px solid #000;" v-for="keys in keysArr">{{titleObj[keys]}}</th>
                </tr>
            </thead>
            <tbody class="table-content" ref="tableContent">
                <tr v-for="item in tableData">
                    <td v-for="keys in keysArr">{{ item[keys] }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>
<script setup>

const props = defineProps({
    style: {
        type: String,
        required: false,
        default: "",
    },
    data: {
        type: Array,
        default: [{ id: "1", name: "名字123", img: "图片123" }, { id: "2", name: "名字23", img: "图片23" }]
    },
    title: {
        type: Object,
        default: {}
    },
    index: {
        type: Boolean,
        default: false
    },
    height: {
        type: Number,
        default: 200
    }
});
let titleObj = reactive({})
let keysArr = reactive([])
let hz = ref()
let tdHeight = 26, //td的高度
    tableHeight = props.height, //table的高度
    tableData = [], //真实展示的列表
    scrollHeight = 0, //@scroll事件滚动的top值
    ScroolNum = 0, //scrollHei能被li高度取余数的整数值。ScroolNum=scrollHei-(scrollHei%liHei)
    showList = 0, //真实展示的条数
    tableDataAll = [], //全部数据的集合
    lastTime = 0, //最后时间
    ele = null;
// 表头dom
const tableHead = ref()
// 表头内容
let tableHeadStr = ref('')
// 内容dom
let tableContent = ref('')
// 内容数据
let tableContentStr = ref('')
// 
let table = ref()


onMounted(() => {

    keysArr = Object.keys(props.title)

    if (keysArr.length === 0) {
        keysArr = Object.keys(props.data[0])

        // keysArr =[tempKeysArr]

        for (var i = 0; i < keysArr.length; i++) {
            titleObj[keysArr[i]] = keysArr[i]
        }

    }else{
        titleObj = props.title
    }

    console.log(titleObj)
    console.log(keysArr)

    tableHeight = props.height
    hz.value.style.height = props.height + 'px'
    // 遍历对象 获取key 和value 动态生成表头div

    // 如果设置展示编号
    let tempTableHeaderStr = ""
    if (props.index) {
        // 增加编号列
        tempTableHeaderStr += `<th style="text-align:center;border:1px solid #000;" class="title-index">编号</th>`
    }
    for (var i = 0; i < keysArr.length; i++) {
        // 动态生成表头
        tempTableHeaderStr += `<th style="text-align:center;border:1px solid #000" class="title-${keysArr[i]}">${props.title[keysArr[i]]}</th>`
    }
    tableHeadStr.value = `<tr>${tempTableHeaderStr}</tr>`
    tableDataAll = props.data; //全部数据集
    // console.log(tableDataAll)
    showList = Math.floor(tableHeight / tdHeight); //计算真实渲染的列表数量
    // console.log(showList)
    tableData = tableDataAll.slice(0, showList); //初始化可视列表的内容
    lastTime = new Date().getTime(); //记录最后一次更新时间


    if (!!ele) { //判断监听元素是否保存到ele字段中
        console.log(ele, 81)
        ele.target.scrollTop = 0; //如果元素存在ele中则将scrollTop初始化为0;
        ScroolNum = 0; //初始化translateY的偏移高度
    }

    renderHtml(tableData)


})

const scroll = function (idx) {

    if (new Date().getTime() - lastTime > 20) { //设置时间间隔，防止滚动事件高频触发消耗内存资源
        // console.log(tableDataAll)
        ele = idx; //保存元素，方便重置scrollTop值
        console.log(idx.target.scrollTop, 96)
        scrollHeight = idx.target.scrollTop; //保存滚动条scrollTop值
        ScroolNum = scrollHeight - (scrollHeight % tdHeight) + 10; //获取已滚动到页面上方不可见的tr元素的总高度（translateY的偏移高度）
        console.log(ScroolNum, 99)
        let len = Math.ceil(ScroolNum / tdHeight); //计算已经有多少个li滚动到页面上方（视图上方用户不可见的数量）
        console.log(len + showList, len)
        tableData = tableDataAll.slice(scrollHeight, scrollHeight + showList); //每次滚动事件后重新计算展示内容（截取的内容对应全部数据集的部分内容）
        // console.log(tableData)
        lastTime = new Date().getTime(); //记录最后一次更新时间
        renderHtml(tableData)
    }
}

const renderHtml = function (arr) {
    console.log(arr)
    let keysArr = Object.keys(props.title)
    tableContentStr.value = ""
    for (var j = 0; j < arr.length; j++) {
        let tempTableStr = ''
        if (props.index) {
            // 增加编号列
            tempTableStr += `<td style="text-align:center;border:1px solid #000" class="title-index">${j + 1}</td>`

        }

        for (var i = 0; i < keysArr.length; i++) {
            // 动态生成表头
            tempTableStr += `<td style="text-align:center;border:1px solid #000" class="content content${i}-${keysArr[i]}">${arr[j][[keysArr[i]]]}</td>`
        }
        tableContentStr.value += `<tr style="height:${tdHeight}px;transform:translateY(${ScroolNum}px)">${tempTableStr}</tr>`

    }
}
</script>
<style scoped>
.main {
    color: #000;
    width: 100%;
    overflow-y: scroll;
}

table {
    width: 97%;
    border-collapse: collapse;
}

th {
    text-align: center;
}

td {
    border: 1px solid #000;
    text-align: center;
}
</style>
